package netty;



import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//netty服务端信息监听类
class ServerListener extends SimpleChannelHandler{

    //通道关闭时会触发
    @Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelClosed(ctx, e);
        System.out.println("channelClosed....通道被关闭");
    }

    //必须建立连接，关闭通道时被触发
    @Override
    public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        super.channelDisconnected(ctx, e);
        System.out.println("channelDisconnected");
    }

    //接受出现异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
        super.exceptionCaught(ctx, e);
        System.out.println("exceptionCaught...出现异常");
    }

    //接受客户端数据

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        super.messageReceived(ctx, e);
        System.out.println("messageReceived...消息接收");
        System.out.println("服务器获取客户端发来的参数:" + e.getMessage());
        ctx.getChannel().write("服务端回应消息：！！！");
    }
}

//netty服务端 netty是非阻塞请求的解决方案之一，保证请求之前等待的代码不会阻塞，之后的代码不会阻塞，照常执行
public class NettyServer {
    public static void main(String[] args) {
        //1.创建netty服务端对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        //2.创建两个线程池 第一个监听端口 nio监听
        ExecutorService books = Executors.newCachedThreadPool();
        ExecutorService wook = Executors.newCachedThreadPool();
        //3.将线程池放入工程
        serverBootstrap.setFactory(new NioServerSocketChannelFactory(books,wook));
        //4.设置管道工程
        serverBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                //传输数据直接为String类型
                pipeline.addLast("decoder",new StringDecoder());
                pipeline.addLast("encoder",new StringEncoder());
                //设置事件监听类
                pipeline.addLast("serverHanlder",new ServerListener());
                return pipeline;
            }
        });
        // 绑定端口号
        serverBootstrap.bind(new InetSocketAddress(8080));
        System.out.println("netty....服务端已启动");
        //测试会不会阻塞
        while (true) {
			try {
				Thread.sleep(2000);
			} catch (Exception e) {
				// TODO: handle exception
			}
			System.out.println("每隔2秒打印.....");
		}

    }
}
